$(function(){
	getChoice();
	function getChoice(){
		$.post("/index.php?m=Admin&c=Customer&a=search",{pageIndex:page.page,pageSize:page.length,select:page.keyword},function(data){
			var data=data.data;
			console.log(data);
			var str="";

			for(x in data){
				// alert(data);
				if(data[x]['sex']=='M'){
					data[x]['sex']="男";
				}else{
					data[x]['sex']="女";
				}
				var dataMember=data[x]['family_member'];
				if(dataMember.length!==0){
					for(var k=0;k<dataMember.length;k++ ){
						if(dataMember[k]['family_id']==page.familyId){
							str+='<tr class="text-c"><td>'+data[x]['id']+'</td><td>'+data[x]['customer_no']+'</td><td>'+data[x]['name']+'</td><td>'+data[x]['sex']+'</td><td>'+data[x]['tel']+'</td><td class="td-status"><a ref="javascript:;" class="label label-permission choiceDelBtn radius  uid-'+data[x]['id']+'" uid="'+data[x]['id']+'">已添加</a></td></tr>';
							break;
						}else{
							if(k==dataMember.length-1){
								str+='<tr class="text-c"><td>'+data[x]['id']+'</td><td>'+data[x]['customer_no']+'</td><td>'+data[x]['name']+'</td><td>'+data[x]['sex']+'</td><td>'+data[x]['tel']+'</td><td class="td-status"><a ref="javascript:;" class="label label-success radius choiceBtn uid-'+data[x]['id']+'" uid="'+data[x]['id']+'">确定</a></td></tr>';
							}
						}
					}
				}else{
					str+='<tr class="text-c"><td>'+data[x]['id']+'</td><td>'+data[x]['customer_no']+'</td><td>'+data[x]['name']+'</td><td>'+data[x]['sex']+'</td><td>'+data[x]['tel']+'</td><td class="td-status"><a href="javascript:;" class="label label-success radius choiceBtn uid-'+data[x]['id']+'" uid="'+data[x]['id']+'">确定</a></td></tr>';
				}
			}
			$(".choiceTr").empty();
			$(".choiceTr").append(str);
		});
	}

	// 键盘事件，搜索触发
	$(window).keyup(function(event){
  		page.keyword=$("#choiceName").val();
  		console.log(page.keyword);
  		getChoice();
	});
	$(document).on("click",".choiceBtn",function(){
		var uid=$(this).attr("uid");
		var familyId=page.familyId;
		  addMember(uid,familyId);
	});
	$(document).on("click",".choiceDelBtn",function(){
		var uid=$(this).attr("uid");
		var familyId=page.familyId;
		  delMember(uid,familyId);
	});
	//添加成员
	function addMember(uid,familyId,appellation){
		$.post("/index.php?m=Admin&c=FamilyMember&a=add",{customer_id:uid,family_id:familyId,appellation:appellation},function(data){
			if(data.stat==1){
				$(".uid-"+uid).text("已添加");
				$(".uid-"+uid).addClass('label-permission').removeClass('label-success').removeClass("choiceBtn").addClass('choiceDelBtn');
			}
		});
	}
	//删除成员
	function delMember(uid,familyId,appellation){
		$.post("/index.php?m=Admin&c=FamilyMember&a=delete",{customer_id:uid,family_id:familyId,appellation:appellation},function(data){
			if(data.stat==1){
				$(".uid-"+uid).text("确定");
				$(".uid-"+uid).removeClass('label-permission').addClass('label-success').addClass("choiceBtn").removeClass('choiceDelBtn');
			}
		});
	}

})